<?php

namespace App\Service\delivery;
use _PHPStan_adbc35a1c\Nette\Neon\Exception;
use App\Model\Applet;
use App\Model\AppletCompany;
use App\Model\AppletPlayletRel;
use App\Model\Company;
use App\Model\PlayletEpisodes;
use App\Model\RechargeGoods;
use App\Model\RechargeTemplate;
use App\Model\RechargeTemplateGoodsRel;
use App\Service\CommicService;
use App\Model\Playlet;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class RechargeTemplateService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);

        $this->userAppletIds = $this->getUserAppletInfo();
    }
    const STATUS_ENABLE  = 1;
    public function Search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $company_id  = $params['company_id'] ?? 0;
        //$applet_id   = $params['applet_id'] ?? 0;
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;
        $applet_ids     = $params['applet_ids'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
//        var_dump(123);
        //获取所拥有的
        if($applet_ids == '1'){
            //获取所有的小程序所绑定的短剧
            $applet_id =  $this->userAppletIds;
        }else{
            $applet_id =  [$applet_ids];
        }
        $query = RechargeTemplate::query()
            ->select(['id','name','status','applet_id','company_id','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }

//        if(!empty($company_id)){
//            $query->where(['company_id' => $company_id]);
//        }
        if(!empty($applet_id)){
            $query->whereIn('applet_id',$applet_id);
        }
        //根据用户获取ID
        $userInfo = $this->getUserAppletInfo(2);
        if($userInfo['role']['is_admin'] != 1){
            $query->where('user_id',$userInfo['id']);
        }
        $query->orwhere('id','1');
        $models = $query->orderBy('updated_at','desc')->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['status_name']    =   self::$commonStatus[$item->status];
            $templateGoods      = $item->template;
            $member = array();
            $convention = array();
            $promotion = array();
            if(!empty($templateGoods)){
                foreach ($templateGoods as $goods){
                    if($goods['type'] == 0){
                        $convention[] = '充 '.($goods['amount']/100).' 元 '.'获得'.$goods['ml_coin'].' + '.$goods['give_coin'].' 币';
                    }
                    if($goods['type'] == 3 && $goods['status'] == 1){
                        $member[] = '充 '.($goods['amount']/100).' 元 '.$goods['name'];
                    }
                    if($goods['type'] == 2 && $goods['status'] == 1){

                        $promotion[] = '充 '.($goods['amount']/100).' 元 '.$goods['name'];

                    }
                }
            }
            if(!empty($item->applet)){
                $data['applet_name']  = $item->applet->name;
            }else{
                $data['applet_name']  = '';
            }
            if(!empty($item->company)){
                $data['company_name']  = $item->company->name;
            }else{
                $data['company_name']  = '';
            }
            $data['convention'] = $convention;
            $data['member'] = $member;
            $data['promotion'] = $promotion;

            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = $selectData;

        return $data;
    }


    public function createOrUpdate(Array $postData, bool $is_update = false, RechargeTemplate $rechargeTemplateInfo = null){

        $name = $postData['name'];
        $status = $postData['status'];
        $applet_id = $postData['applet_id'];

        //根据用户获取ID
        $userInfo = $this->getUserAppletInfo(2);
        $company_id = $userInfo['company_id'];

        $templateStatus = [true => 1,false => 0];

        $model = !empty($rechargeTemplateInfo)? $rechargeTemplateInfo : new RechargeTemplate();
        $model->name = $name;
        $model->user_id = $userInfo['id'];
        $model->status = $status;
        Db::beginTransaction();

        try {

            //查看公司是否存在
            $companyData = Company::query()->where(['id' => $company_id])->exists();
            if(empty($companyData)){
                throw new \Exception('公司不存在');
            }
            //查找小程序是否存在
            $appletData = Applet::query()->where(['id' => $applet_id])->exists();
            if(empty($appletData)){
                throw new \Exception('请选择小程序');
            }
            //查看小程序和公司是否存在绑定关系
            $appletCompanyData = AppletCompany::query()->where(['company_id' => $company_id,'applet_id' => $applet_id])->exists();
            if(empty($appletCompanyData)){
                throw new \Exception('公司和小程序不存在绑定关系小程序');
            }
            $model->applet_id = $applet_id;
            $model->company_id = $company_id;

            if($model->save()){
                $template_id = $model->id;

                $conventions = $postData['convention'];
                if(empty($conventions)){
                    throw new \Exception('常规档位数据为空');
                }
                $members = $postData['member'];
                if(empty($members)){
                    throw new \Exception('会员档位数据为空');
                }
                $promotions = $postData['promotion'];
                if(empty($promotions)){
                    throw new \Exception('促销档位数据为空');
                }
                $sortInfo = $postData['sortInfo'];
                if(empty($sortInfo)){
                    throw new \Exception('播放页充值页面设置不能为空');
                }
                //保存模板到rechargeGoods 中
                if($is_update){

                    foreach ($conventions as $convention){
                        if(empty($convention['amount'])) {
                            throw new \Exception($convention['name'].':充值价格不能为空');
                        }
                        $amount = floatval($convention['amount']);
                        $amount = intval($amount*100);
                        if(empty($convention['id'])){


                            RechargeGoods::create(
                                [
                                    'name' => $convention['name'], 'amount' =>$amount, 'ml_coin' => $amount,
                                    'give_coin' => $convention['give_coin'], 'type' => 1, 'status' => $templateStatus[$convention['status']],
                                    'day' => $convention['day'], 'recharge_template_id' => $template_id,'value' => $convention['value'],
                                ]
                            );
                        }else{
                            $updateData = [
                                'amount' => $amount,
                                'ml_coin' => $amount,
                                'give_coin' => $convention['give_coin'],
                                'status' => $templateStatus[$convention['status']]
                            ];
                            RechargeGoods::query()->where(['id' => $convention['id']])->update($updateData);
                        }
                    }
                    foreach ($members as $member){
                        if(empty($member['amount']) && $member['status'] == 1) {
                            throw new \Exception($member['name'].':充值价格不能为空');
                        }
                        $amount = floatval($member['amount']);
                        $amount = intval($amount*100);
                        if(empty($member['id'])){
                            throw new \Exception($member['name'].':ID不存在');
                        }
                        $updateData = ['amount' => $amount,'status' => $templateStatus[$member['status']]];
                        RechargeGoods::query()->where(['id' => $member['id']])->update($updateData);

                    }
                    foreach ($promotions as $promotion){
                        if(empty($promotion['amount']) && $promotion['status'] == 1) {
                            throw new \Exception($promotion['name'].':充值价格不能为空');
                        }
                        $amount = floatval($promotion['amount']);
                        $amount = intval($amount*100);
                        $updateData = ['amount' => $amount,'status' => $templateStatus[$promotion['status']]];
                        RechargeGoods::query()->where(['id' => $promotion['id']])->update($updateData);
                    }
                }else{

                    foreach ($conventions as $convention){
                        if(empty($convention['amount'])) {
                            throw new \Exception($convention['name'].':充值价格不能为空');
                        }
                        $amount = floatval($convention['amount']);
                        $amount = intval($amount*100);
                        RechargeGoods::create(
                            [
                                'name' => $convention['name'], 'amount' => $amount, 'ml_coin' => $amount,
                                'give_coin' => $convention['give_coin'], 'type' => 1, 'status' => $templateStatus[$convention['status']],
                                'day' => $convention['day'], 'recharge_template_id' => $template_id,'value' => $convention['value'],
                            ]
                        );
                    }

                    foreach ($members as $member){
                        if(empty($member['amount']) && $member['status'] == 1) {
                            throw new \Exception($member['name'].':充值价格不能为空');
                        }
                        $amount =  floatval($member['amount']);
                        $amount = intval($amount*100);
                        RechargeGoods::create(
                            [
                                'name' => $member['name'], 'amount' => $amount, 'type' => 3, 'status' => $templateStatus[$member['status']],
                                'day' => $member['day'], 'recharge_template_id' => $template_id,'value' => $member['value'],
                            ]
                        );
                    }
                    foreach ($promotions as $promotion){
                        if(empty($promotion['amount']) && $promotion['status'] == 1) {
                            throw new \Exception($promotion['name'].':充值价格不能为空');
                        }
                        $amount = floatval($promotion['amount']);
                        $amount = intval($amount*100);
                        RechargeGoods::create(
                            [
                                'name' => $promotion['name'], 'amount' => $amount, 'type' => 2, 'status' => $templateStatus[$promotion['status']],
                                'day' => $promotion['day'], 'recharge_template_id' => $template_id,'value' => $promotion['value'],
                            ]
                        );
                    }
                }

                //删除对应表的数据
                RechargeTemplateGoodsRel::query()->where(['recharge_template_id' => $template_id])->delete();
                //查找对应的唯一值的数据
                $rechargeGoodsData = RechargeGoods::query()->whereIn('value',$sortInfo)->where(['recharge_template_id' => $template_id,'status' => RechargeGoods::STATUS_SHOW])->select(['id','value'])->get()->toArray();
                if(empty($rechargeGoodsData)){
                    throw new \Exception('没有对应的模板数据');
                }else{

                    $goodsKeyVal = array();

                    foreach ($rechargeGoodsData as $rechargeGoodsValue){
                        $goodsKeyVal[$rechargeGoodsValue['value']] = $rechargeGoodsValue['id'];
                    }
                    $sortNum = count($sortInfo);
                    foreach ($sortInfo as $sortValue){
                        if(!empty($goodsKeyVal[$sortValue])){
                            RechargeTemplateGoodsRel::create(
                                [
                                    'recharge_goods_id' =>$goodsKeyVal[$sortValue],
                                    'recharge_template_id' => $template_id,
                                    'sort' => $sortNum,
                                ]
                            );
                            $sortNum = $sortNum-1;
                        }
                    }
                }
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{

                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
            }

        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }

    public function recombinationData(Array $selectData){
        $result = array();
        $result['name'] = $selectData['name'];
        $result['status'] = $selectData['status'];
        $result['company_id'] = $selectData['company_id'];
        $result['applet_id'] = $selectData['applet_id'];
        $rechargeGoods = RechargeGoods::query()->where(['recharge_template_id' => $selectData['id']])->get()->toArray();

        $member = array();
        $convention = array();
        $promotion = array();
        $sortInfo = array();
        $typeName = [1 => 'convention' ,3 => 'member',2 => 'promotion'];
        if(!empty($rechargeGoods)){
            foreach ($rechargeGoods as $goods){
                $type_name = $typeName[$goods['type']];
                $$type_name[] = [
                    'id' => $goods['id'],
                    'name' => $goods['name'],
                    'amount' => $goods['amount']/100,
                    'give_coin' => $goods['give_coin'],
                    'status' => ($goods['status'] == 1) ? true : false,
                    'type' => $goods['type'],
                    'day' => $goods['day'],
                    'value' => $goods['value'],

                ];
            }
        }

        $rechargeGoodsIds = RechargeTemplateGoodsRel::query()->where(['recharge_template_id' =>$selectData['id']])->orderBy('sort','desc')->pluck('recharge_goods_id');


        $rechargeGoodsSortData = RechargeGoods::query()->whereIn('id',$rechargeGoodsIds)->select(['id','value'])->get()->toArray();
        $goodsKeyVal = array();
        foreach ($rechargeGoodsSortData as $goodsVal){
            $goodsKeyVal[$goodsVal['id']] = $goodsVal['value'];
        }
        foreach ($rechargeGoodsIds as $good_id){
            if(!empty($goodsKeyVal[$good_id])){
                $sortInfo[] = $goodsKeyVal[$good_id];
            }
        }
        $result['convention'] = $convention;
        $result['member'] = $member;
        $result['promotion'] = $promotion;
        $result['sortInfo'] = $sortInfo;
        return $result;
    }
}